<template>
  <ele-modal
    form
    width="95%"
    :model-value="modelValue"
    :title="title"
    @update:modelValue="updateModelValue"
  >
    <ele-card :body-style="{ paddingTop: '8px' }">
      <!-- 表格 -->
      <ele-pro-table
        ref="tableRef"
        :columns="columns"
        :datasource="datasource"
        :show-overflow-tooltip="true"
        highlight-current-row
        v-model:selections="selections"
        border
        stripe
        row-key="id"
        row-click-checked
        @done="onDone"
      >
        <template #toolbar="{}">
          <el-button
            type="primary"
            size="small"
            @click="choose"
            v-if="props.data.status < 5"
          >
            保存选择
          </el-button>
        </template>
        <template #rebate="{ row }">
          {{ row.rebate_amount }}（{{ row.rebate }}%）
        </template>

        <template #insurance_salesman="{ row }">
          <span>{{ row.insurance_salesman }}</span>
        </template>
        <template #insurance="{ row }">
          {{ row.insurance }}
        </template>
        <!-- <template #price="{ row }">
          <span class="pointer blue" @click="openDetail(row)">{{
            row.price
          }}</span>
        </template> -->
        <template #totalPrice="{ row }">
          <span :class="priceClass(row.raise_price)">{{ row.totalPrice }}</span>
        </template>

        <template #otherPrice="{ row }">
          {{ row.otherPrice }}
        </template>

        <template #s_time="{ row }">
          {{ row.sTime }}
        </template>
        <template #e_time="{ row }">
          {{ row.eTime }}
        </template>

        <template #img="{ row }">
          <span
            v-if="row.images !== ''"
            class="pointer blue"
            @click="openImages(row.offerImages)"
            >查看</span
          >
          <span v-else>无</span>
        </template>

        <template #payImage="{ row }">
          <span
            v-if="row.payImages !== ''"
            class="pointer blue"
            @click="openImages(row.payImages)"
            >查看</span
          >
          <span v-else>无</span>
        </template>
        <template #pdf="{ row }">
          <span class="pointer blue" @click="openPdf(row.pdf)">查看</span>
        </template>

        <!-- <template #action="{ row }">
          <el-button-group>
            <el-button type="success" size="small" @click="choose(row)">
              选择
            </el-button>
          </el-button-group>
        </template> -->
      </ele-pro-table>
    </ele-card>

    <!-- 图片 -->
    <images v-model="showImages" :data="imageList" />
  </ele-modal>
</template>

<script setup>
  import { ref, watch, computed, nextTick } from 'vue';
  import { EleMessage } from 'ele-admin-plus/es';
  import { pageTradeInsurance, updateTradeInsurance } from '@/api/company';
  const emit = defineEmits(['done', 'update:modelValue']);

  import Images from './images.vue';

  const props = defineProps({
    /** 弹窗是否打开 */
    modelValue: Boolean,
    data: Object
  });
  const title = ref('');
  /** 表格实例 */
  const tableRef = ref(null);

  const priceClass = (value) => {
    return value > 0 ? 'red' : 'blue';
  };

  /** 表格列配置 */
  const columns = computed(() => {
    const cols = [];

    if (props.data.status == 0 || props.data.status == 4) {
      cols.push({
        type: 'selection',
        columnKey: 'choose',
        width: 50,
        align: 'center',
        fixed: 'left'
      });
    }

    cols.push(
      {
        width: 80,
        prop: 'id',
        label: '编号'
      },
      {
        width: 100,
        prop: 'plate_number',
        label: '所属车辆'
      },
      {
        width: 100,
        prop: 'cate',
        label: '类型'
      },
      {
        slot: 'insurance',
        label: '保险公司'
      },
      {
        slot: 'insurance_salesman',
        label: '保险业务员',
        width: 120
      },
      {
        width: 100,
        slot: 'totalPrice',
        label: '总价'
      },
      {
        width: 100,
        prop: 'price',
        label: '价格'
      },
      {
        width: 100,
        slot: 'otherPrice',
        label: '加价/车船'
      },
      {
        width: 150,
        slot: 'rebate',
        label: '返点'
      },
      {
        width: 180,
        slot: 's_time',
        label: '开始日期'
      },
      {
        width: 180,
        slot: 'e_time',
        label: '结束日期'
      },
      {
        width: 100,
        slot: 'img',
        label: '报价图片',
        align: 'center'
      }
    );
    if (props.data.status == 200) {
      cols.push(
        {
          width: 100,
          slot: 'payImage',
          label: '付款信息',
          align: 'center'
        },
        {
          width: 100,
          slot: 'pdf',
          label: '电子保单',
          align: 'center'
        }
      );
    }

    return cols;
  });
  /** 表格数据请求完成事件 */
  const onDone = () => {
    // 回显 id 为 45、47、48 的数据的复选框
    nextTick(() => {
      tableRef.value?.setSelectedRowKeys?.(chooseIds.value);
    });
  };

  /** 选择保险 */
  const choose = () => {
    const rows = selections.value;
    let unique = isUniqueCate(rows);
    if (!unique) {
      EleMessage.warning('每种保险只能选择一条');
      return false;
    }
    console.log(rows, '艹艹艹');

    updateTradeInsurance({
      vehicle_id: props.data.vehicle_id,
      rows: JSON.stringify(rows),
      trade_id: props.data.id
    })
      .then((res) => {
        emit('done');
        console.log(res);
      })
      .catch((e) => {
        console.log(e);
      });
  };

  const isUniqueCate = (array) => {
    const seen = new Set(); // 用 Set 来存储已出现的 cate 值
    for (const item of array) {
      if (seen.has(item.cate)) {
        return false; // 如果 cate 已经存在，返回 false
      }
      seen.add(item.cate); // 否则添加到 Set 中
    }
    return true; // 如果遍历完成没有重复，返回 true
  };

  /** 表格选中数据 */
  const selections = ref([]);
  /** 表格数据源 */
  var chooseIds = ref([]);
  const datasource = async ({ page, limit, where, orders }) => {
    const result = await pageTradeInsurance({
      ...where,
      ...orders,
      page,
      limit,
      status: props.data.status < 5 ? 0 : '',
      trade_id: props.data.status < 5 ? '' : props.data.id,
      vehicle_id: props.data.vehicle_id,
      choose: props.data.status < 5 ? '' : 1
    });
    chooseIds.value = result.chooseIds;
    return result;
  };

  const openPdf = (url) => {
    window.open(url);
  };

  /** 查看图片 */
  const imageList = ref([]);
  const showImages = ref(false);
  const openImages = (data) => {
    imageList.value = data;
    showImages.value = true;
  };

  /** 更新modelValue */
  const updateModelValue = (value) => {
    emit('update:modelValue', value);
  };

  watch(
    () => props.modelValue,
    (modelValue) => {
      if (modelValue) {
        title.value = props.data.plate_number + '的保险报价列表';
      } else {
        console.log('关闭');
      }
    }
  );
</script>
